package com.siyoumi.sh.modules.ccb;

import com.alibaba.fastjson.JSONObject;
import com.siyoumi.sh.component.XRedis;
import com.siyoumi.sh.modules.ccb.entity.CcbApiToken;
import com.siyoumi.sh.modules.ccb.entity.CcbProduct;
import com.siyoumi.sh.modules.ccb.entity.CcbProductData;
import com.siyoumi.sh.modules.ccb.entity.CcbUser;
import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.common.send_msg.TlSendMsg;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//建行ccb,检查是否有E卡
@Slf4j
public class CcbPrizeStockHandle
        extends CcbHandleBase
        implements IHandle {


    @SneakyThrows
    @Override
    public void run() {
        TlSendMsg.remove();

        List<CcbApiToken> tokenArr = getArrToken();
        if (tokenArr.size() <= 0) {
            log.error("未配置CCB_TOKEN");
            return;
        }
        log.info("BEGIN: {}", XDate.toDateTimeString());

        CcbApiToken apiToken = getArrToken().get(0);

        logAndSet(TlSendMsg.get(), "**CCB检查兑换中心发放** \n\n");

        CcbProductData productData = getProductToken(apiToken, true);
        log.debug("调用兑换中心接口参数: {}", XJson.toJSONString(productData));
        if (productData == null) {
            //发信息
            sendMsg(TlSendMsg.get().toString());
            return;
        }

        List<String> keywordList = new ArrayList<>();
        keywordList.add("京东");
        keywordList.add("E卡");
        //keywordList.add("油卡");
        //keywordList.add("天猫");
        logAndSet(TlSendMsg.get(), XStr.format("搜索关键词: {0} \n\n", keywordList.stream().collect(Collectors.joining(","))));

        List<CcbProduct> list = new ArrayList<>();
        List<CcbProduct> listSuper = queryProductObj(productData.getToken(), productData.getChannelId(), "TCC2022032800000574"); //商超
        sleepAndLog(1);
        List<CcbProduct> listCar = queryProductObj(productData.getToken(), productData.getChannelId(), "TCC2023021700002749"); //文旅
        sleepAndLog(1);
        List<CcbProduct> listLive = queryProductObj(productData.getToken(), productData.getChannelId(), "TCC2022032800000578"); //生活
        list.addAll(listSuper);
        list.addAll(listCar);
        list.addAll(listLive);

        List<CcbProduct> searchList = list.stream().filter(item -> {
            for (String kw : keywordList) {
                if (XStr.contains(item.getActivityName(), kw) && item.getRemainingInventory() > 0) {
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        if (searchList.size() <= 0) {
            logAndSet(TlSendMsg.get(), "**没有符合的商品** \n\n");

            String notFindKey = "ccb_prize|not_find";
            if (!XRedis.getBean().exists(notFindKey)) {
                sendMsg(TlSendMsg.get().toString(), "没有符合的商品");

                XRedis.getBean().setEx(notFindKey, "1", XDate.now().plusHours(6));
            }
        } else {
            logAndSet(TlSendMsg.get(), "**符合的商品** \n\n");
            for (CcbProduct item : searchList) {
                logAndSet(TlSendMsg.get(), XStr.format("{0},剩余:{1} \n\n"
                        , item.getActivityName()
                        , item.getRemainingInventory().toString())
                );
            }

            sendMsg(TlSendMsg.get().toString(), "存在符合商品");
        }

        TlSendMsg.remove();
        log.info("END: {}", XDate.toDateTimeString());
    }


    private CcbProductData getProductToken(CcbApiToken apiToken, Boolean getCache) {
        String redisKey = "product_token|" + apiToken.getName();
        if (getCache) {
            String json = XRedis.getBean().get(redisKey);
            if (XStr.hasAnyText(json)) {
                return XJson.parseObject(json, CcbProductData.class);
            }
        }

        CcbUser user = getZhcToken(apiToken, null);
        if (user == null) {
            return null;
        }
        XReturn rLogin = zhcTokenAuthLogin(user.getZhcToken());
        if (rLogin.err()) {
            logAndSet(TlSendMsg.get(), "登陆zhc_toekn失败：" + rLogin.getErrMsg() + "\n\n");
            return null;
        }

        sleepAndLog(1);
        CcbProductData productData = getChannelcode(user.getZhcToken());
        if (productData == null) {
            return null;
        }

        sleepAndLog(1);
        XReturn r = getTokenApi(productData.getChannelId(), productData.getChannelKey());
        if (r.err()) {
            logAndSet(TlSendMsg.get(), "获取奖品token：" + r.getErrMsg() + "\n\n");
            return null;
        }

        String token = r.getData("token", "");
        if (XStr.isNullOrEmpty(token)) {
            logAndSet(TlSendMsg.get(), "奖品token为空 \n\n");
            return null;
        }
        productData.setToken(token);

        //6小时
        XRedis.getBean().setEx(redisKey, XJson.toJSONString(productData), 3600);

        return productData;
    }


    //获取渠道code
    private CcbProductData getChannelcode(String zhcToken) {
        String url = "https://m3.dmsp.ccb.com/api/businessCenter/user/getUserSecretKey?zhc_token=" + XStr.urlEnc(zhcToken);

        Map<String, String> mapHeader = new HashMap<>();
        mapHeader.put("zhc_token", zhcToken);
        mapHeader.put("User-Agent", userAgent);

        XReturn r = postJson(url, mapHeader, null);
        if (r.err()) {
            logAndSet(TlSendMsg.get(), "获取渠道code失败：" + r.getErrMsg() + "\n\n");
            return null;
        }
        JSONObject data = (JSONObject) r.get("data");
        String zhcCcCoinChannelCode = data.getString("zhcCcCoinChannelCode");
        String zhcCcCoinKey = data.getString("zhcCcCoinKey");

        CcbProductData product = new CcbProductData();
        product.setChannelId(zhcCcCoinChannelCode);
        product.setChannelKey(zhcCcCoinKey);
        return product;
    }

    //获取奖品token
    @SneakyThrows
    private XReturn getTokenApi(String channelId, String zhcCcCoinKey) {
        String url = "https://cy.cloud.ccb.com/gateway/user-server/user/promised/login";

        String referer = XStr.format("https://cy.cloud.ccb.com/qymall/ccbean/ccbean_mall_index?page=exchange&encString={0}&channel_no={1}&CCB_Chnl=6000189", zhcCcCoinKey, channelId);

        Map<String, String> mapHeader = new HashMap<>();
        mapHeader.put("ChannelId", channelId);
        mapHeader.put("Channel", "JH-0007");
        mapHeader.put("User-Agent", userAgent);
        mapHeader.put("Referer", referer);

        Map<String, Object> mapPost = new HashMap<>();
        Map<String, Object> mapPostData = new HashMap<>();
        mapPost.put("data", mapPostData);
        mapPostData.put("channel_no", channelId);
        mapPostData.put("encString", XStr.urlDec(zhcCcCoinKey));

        XHttpClient client = XHttpClient.getInstance();
        CloseableHttpResponse response = client.postReturnObj(url, mapHeader, mapPost);
        String returnStr = EntityUtils.toString(response.getEntity());
        log.debug("return_str: {}", returnStr);

        XReturn r = paresR(returnStr);
        if (r.err()) {
            return r;
        }

        Header token = response.getFirstHeader("token");
        if (XStr.isNullOrEmpty(token.getValue())) {
            return XReturn.getR(20119, "token不存在");
        }
        r.setData("token", token.getValue());

        return r;
    }


    private List<CcbProduct> queryProductObj(String token, String channelId, String channelCategoryId) {
        XReturn r = queryProduct(token, channelId, channelCategoryId);
        if (r.err()) {
            logAndSet(TlSendMsg.get(), "获取zhc_toekn失败：" + r.getErrMsg() + "\n\n");
            return null;
        }

        String listJson = XJson.toJSONString(r.getData("data"));
        List<CcbProduct> list = XJson.parseArray(listJson, CcbProduct.class);

        return list;
    }

    //获取商品列表
    private XReturn queryProduct(String token, String channelId, String channelCategoryId) {
        String url = "https://cy.cloud.ccb.com/gateway/goods-server/goods/ccBeanCategory/queryProduct";

        Map<String, String> mapHeader = new HashMap<>();
        mapHeader.put("Authorization", token);
        mapHeader.put("User-Agent", userAgent);

        Map<String, Object> mapPost = new HashMap<>();
        mapPost.put("channelId", channelId);
        mapPost.put("channel", "JH-0007");
        mapPost.put("channelCategoryId", channelCategoryId);
        mapPost.put("city", "440100");
        mapPost.put("province", "440100");
        mapPost.put("type", "");

        XReturn r = postJson(url, mapHeader, mapPost);
        if (r.err()) {
            return r;
        }

        return r;
    }
}
